package com.mpsc.mq.util;

import com.alibaba.fastjson.JSON;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import com.mpsc.api.annotation.ESAnnotation;
import com.mpsc.api.annotation.ESField;
import com.mpsc.api.bean.ArticleEntity;
import com.mpsc.api.unit.DateUtil;
import com.mpsc.api.unit.StringUtil;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.ScoreSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.*;

public class ElasticSearchUtil<范围匹配RangeQuery> implements Serializable {

    public static TransportClient transportClient = null;

    private static String ES_HOSTS = "192.168.1.13:9309";
    private static String ES_CLUSTER_NAME = "elasticx-dc";


    public static void main(String[] args) throws Exception {
        init(ES_HOSTS, ES_CLUSTER_NAME);
        //一、关于es mapping 操作
        //1、创建es map
        //createMapping(ArticleEntity.class);
        //2、获取mapping信息
        //Map<String, String> mapping = selectMapping(ArticleEntity.class);
        //3、删除mapping信息
        //boolean delState = deleteEsIndex(ArticleEntity.class);
        //4、获取mapping信息
        // Map<String, String> mappings = selectMapping(ArticleEntity.class);

        //二、对数据增删改查操作
        List<ArticleEntity> articleList = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            ArticleEntity save = new ArticleEntity();
            save.setId(i + "");
            save.setArticleName("疯狂的小蘑菇");
            save.setAuthor("李商隐");
            save.setCreateTime(new Date());
            save.setRemark("一个索引中的所有类型具有共享的字段和设置。用 default 映射来指定公用设置会更加方便，而不是每次创建新的类型时重复操作");
            articleList.add(save);
        }
        //1、添加单条数据
        // saveSingle(article);
        //2、添加多条数据
        //saveList(articleList);

        ArticleEntity article = new ArticleEntity();
        article.setId("2");
        article.setArticleName("疯狂的小蘑菇");
        article.setAuthor("李商隐");
        article.setCreateTime(new Date());
        article.setRemark("当匹配对象为中文时，建议使用");
        //1、更新一条数据
        //updateSingle(article);
        //2、批量更新数据
//        List<ArticleEntity> updateList = new ArrayList<>();
//        for (int i = 2; i < 12; i++) {
//            ArticleEntity article1 = new ArticleEntity();
//            article1.setId(i + "");
//            article1.setArticleName("牵着蜗牛逛街");
//            article1.setAuthor("李煜");
//            article1.setCreateTime(new Date());
//            article1.setRemark("一个索引中的所有类型具有共享的字段和设置。用 default 映射来指定公用设置会更加方便，而不是每次创建新的类型时重复操作");
//            updateList.add(article1);
//        }
        //updateList(updateList);

        //1、根据id删除单条数据
        //deleteSingle(articleres);
        //2、根据id批量删除数据
        List<String> idList = new ArrayList<>();
        idList.add("7");
        idList.add("6");
        //deleteList(ArticleEntity.class,idList);

        //1、根据id查询单挑数据
        //ArticleEntity articleres = getObjectById(ArticleEntity.class, "10");
        //2、根据id批量查询数据
        //List<ArticleEntity> list = getObjectByIdList(ArticleEntity.class, idList);

        //3、分页查询所有数据
        //1、指定此查询
        //MatchQueryBuilder builder = QueryBuilders.matchQuery("author", "李白");
        //2、模糊查询
        //WildcardQueryBuilder builder = QueryBuilders.wildcardQuery("remark", "一*");

        //3、多个条件一起查询
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        MatchQueryBuilder matchBuilder = QueryBuilders.matchQuery("author", "李白");
        WildcardQueryBuilder wildcardBuilder = QueryBuilders.wildcardQuery("remark", "一个*");
        //3.1两个条件必须都满足
        //builder.must(matchBuilder);
        //builder.must(wildcardBuilder);
        //3.2 只需满足其中一个条件
        builder.should(matchBuilder);
        builder.should(wildcardBuilder);
        builder.filter(QueryBuilders.rangeQuery("price").gte(60).lte(100));
        //4、范围匹配RangeQuery
        //builder.filter(QueryBuilders.rangeQuery("price").gte(60).lte(100));
        //精确查询
        //builder.filter(QueryBuilders.termQuery("author", "李白"));

        //5、设置author 10倍权重
        //MultiMatchQueryBuilder multiBuilder = QueryBuilders.multiMatchQuery("李白", "articleName", "author").field("author", 10);
        //multiBuilder.minimumShouldMatch("80%");
        //builder.must(multiBuilder);

        List<ArticleEntity> asearchList = searchPage(ArticleEntity.class, builder, 0, 100);
        for (ArticleEntity ae : asearchList) {
            System.out.println(ae.toString());
        }

        System.out.println("---------------");
    }

    public static void init(String esHosts, String clusterName) {
        Settings settings = Settings.builder().put("cluster.name", clusterName)
                //.put("tclient.transport.sniff", true)
                .build();// 自动嗅探整个集群的状态，把集群中其它机器的ip地址加到客户端中
        transportClient = new PreBuiltTransportClient(settings);
        String[] nodes = esHosts.split(",");
        for (String node : nodes) {
            String[] hostPort = node.split(":");
            if (hostPort.length == 2) {
                try {
                    transportClient.addTransportAddress(
                            new InetSocketTransportAddress(InetAddress.getByName(hostPort[0].trim()), Integer.parseInt(hostPort[1].trim())));
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }
    }


    public static <T> List<T> searchPage(Class<T> clx, QueryBuilder queryBuilder, int from, int size) throws Exception {
        List<T> resultList = new ArrayList<>();
        ESAnnotation annotation = clx.getAnnotation(ESAnnotation.class);
        if (null == annotation) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解");
        }
        String index = annotation.index();//索引字段
        String type = annotation.type();// 类型
        if (StringUtils.isEmpty(index) || StringUtils.isEmpty(type)) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解属性 indexName 与 typeName");
        }
        //创建查询builder
        SearchSourceBuilder searchBuilder = new SearchSourceBuilder();
        //1、搜索全部内容
        //searchBuilder.query(QueryBuilders.matchAllQuery());

        //2、排序
        // 默认排序。根据_score倒序
        //searchBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC));
        // 根据_id升序
        //searchBuilder.sort(new FieldSortBuilder("id").order(SortOrder.ASC));

        //3、 设置源字段过虑,第一个参数结果集包括哪些字段，第二个参数表示结果集不包括哪些字段
        //searchBuilder.fetchSource(new String[]{"articleName","id"},new String[]{"createTime"});


        //4、 高亮查询
        //HighlightBuilder highlightBuilder = new HighlightBuilder();
        //highlightBuilder.preTags("<em>"); // 高亮前缀
        //highlightBuilder.postTags("</em>"); // 高亮后缀
        //highlightBuilder.fields().add(new HighlightBuilder.Field("name")); // 高亮字段
        // 添加高亮查询条件到搜索源
        //searchBuilder.highlighter(highlightBuilder);

        searchBuilder.query(queryBuilder);
        searchBuilder.from(from).size(size);
        //创建查询request
        SearchRequest request = new SearchRequest();
        request.indices(index).types(type);
        request.source(searchBuilder);
        SearchResponse response = getClient().search(request).get();
        SearchHit[] hits = response.getHits().internalHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getId());
            Map<String, Object> source = hit.getSource();
            if (null != source && source.size() > 0) {
                resultList.add(mapToPOJO(hit.getSource(), clx));
            }
        }
        return resultList;
    }


    /**
     * 获取TransportClient
     */
    public static TransportClient getClient() {
        return transportClient;
    }

    /**
     * 根据id批量删除数据
     *
     * @param clx    es表对应类的class
     * @param idList 主键id集合
     * @return bulkResponse
     */
    public static <T>BulkResponse deleteList(Class<T> clx, List<String> idList) throws Exception {
        BulkRequest request = new BulkRequest();
        ESAnnotation annotation = clx.getAnnotation(ESAnnotation.class);
        if (null == annotation) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解");
        }
        String index = annotation.index();//索引字段
        String type = annotation.type();// 类型
        if (StringUtils.isEmpty(index) || StringUtils.isEmpty(type)) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解属性 indexName 与 typeName");
        }
        if (null != idList && idList.size() > 0) {
            for (String id : idList) {
                request.add(new DeleteRequest().index(index).type(type).id(id));
            }
        }

        BulkResponse responses = getClient().bulk(request).get();
        return responses;
    }

    /**
     * 根据id删除单条数据
     *
     * @author feijin@iflytek.com
     * @date 2018年6月14日 下午2:44:43
     */
    public static <T>DeleteResponse deleteSingle(T obj) {
        //获取类上配置的注解
        ESAnnotation annotation = obj.getClass().getAnnotation(ESAnnotation.class);
        if (null == annotation) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解");
        }
        String index = annotation.index();//索引字段
        String type = annotation.type();// 类型

        if (StringUtils.isEmpty(index) || StringUtils.isEmpty(type)) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解属性 indexName 与 typeName");
        }
        DeleteResponse response = null;
        try {
            Field field = obj.getClass().getDeclaredField("id");
            field.setAccessible(true);
            String id = (String) field.get(obj);
            response = getClient().prepareDelete(index, type, id).get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }


    /**
     * 根据id批量更新es数据库中数据信息
     *
     * @param list 批量更新数据
     * @return bulkResponse
     */
    public static <T>BulkResponse updateList(List<T> list) throws Exception {
        if (null == list || list.size() == 0) {
            throw new RuntimeException("传入的list参数不存在！");
        }
        //用于保存批量修改的请求
        BulkRequest blkRequest = new BulkRequest();
        //获取类上配置的注解
        ESAnnotation annotation = list.get(0).getClass().getAnnotation(ESAnnotation.class);
        if (null == annotation) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解");
        }
        String index = annotation.index();//索引字段
        String type = annotation.type();// 类型
        if (StringUtils.isEmpty(index) || StringUtils.isEmpty(type)) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解属性 indexName 与 typeName");
        }
        Field[] fields = list.get(0).getClass().getDeclaredFields();
        String esField = null;
        ESField esfield = null;
        String primary = "";
        for (Object obj : list) {
            XContentBuilder builder = XContentFactory.jsonBuilder().startObject();
            for (Field df : fields) {
                esField = df.getName();
                df.setAccessible(true);
                if (null != df.get(obj)) {
                    esfield = df.getAnnotation(ESField.class);
                    if (null != esfield) {
                        esField = esfield.name();
                    }
                    if (df.getType() == Date.class) {
                        builder.field(esField, ((Date) df.get(obj)).getTime());
                    } else {
                        builder.field(esField, df.get(obj));
                    }
                    //获取es中的主键
                    if (df.getName().equals("id")) {
                        primary = (String) df.get(obj);
                    }
                }
            }
            builder.endObject();
            UpdateRequest uRequest = new UpdateRequest().index(index).type(type).id(primary).doc(builder);
            blkRequest.add(uRequest);
        }
        BulkResponse response = getClient().bulk(blkRequest).get();
        return response;
    }

    /**
     * 根据Id更新数据，
     *
     * @param obj 更新数据的实体类
     *            <p>
     */
    public static <T>UpdateResponse updateSingle(T obj) throws Exception {
        //获取类上配置的注解
        ESAnnotation annotation = obj.getClass().getAnnotation(ESAnnotation.class);
        if (null == annotation) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解");
        }
        String index = annotation.index();//索引字段
        String type = annotation.type();// 类型

        if (StringUtils.isEmpty(index) || StringUtils.isEmpty(type)) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解属性 indexName 与 typeName");
        }
        Field primary = obj.getClass().getDeclaredField("id");
        primary.setAccessible(true);
        String id = (String) primary.get(obj);
        XContentBuilder builder = XContentFactory.jsonBuilder().startObject();
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        String esField = null;
        ESField esfield = null;
        for (Field df : declaredFields) {
            esField = df.getName();
            df.setAccessible(true);
            if (null != df.get(obj)) {
                esfield = df.getAnnotation(ESField.class);
                if (null != esfield) {
                    esField = esfield.name();
                }
                if (df.getType() == Date.class) {
                    builder.field(esField, ((Date) df.get(obj)).getTime());
                } else {
                    builder.field(esField, df.get(obj));
                }
            }
        }
        builder.endObject();
        UpdateRequest uRequest = new UpdateRequest().index(index).type(type).id(id).doc(builder);
        UpdateResponse response = getClient().update(uRequest).get();
        return response;
    }


    /**
     * 新增数据，类需要添加@ESAnnotation注解
     *
     * @param obj 需要保存类对象
     */
    public static <T>void saveSingle(T obj) {
        //获取类上配置的注解
        ESAnnotation annotation = obj.getClass().getAnnotation(ESAnnotation.class);
        if (null == annotation) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解");
        }
        String index = annotation.index();//索引字段
        String type = annotation.type();// 类型

        if (StringUtils.isEmpty(index) || StringUtils.isEmpty(type)) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解属性 indexName 与 typeName");
        }

        try {
            String json = JSON.toJSONString(obj);
            Field field = obj.getClass().getDeclaredField("id");
            field.setAccessible(true);
            String id = (String) field.get(obj);
            IndexResponse response = getClient()
                    .prepareIndex(index, type, id)
                    .setSource(json, XContentType.JSON)
                    .get();
            System.out.println("response.version():" + response.getResult());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量保存数据
     *
     * @param list 批量保存的数据
     */
    public static <T>void saveList(List<T> list) {
        if (CollectionUtils.isEmpty(list)) {
            throw new RuntimeException("传入的数据不能为null");
        }
        Object t0 = list.get(0);
        ESAnnotation annotation = t0.getClass().getAnnotation(ESAnnotation.class);
        if (null == annotation) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解");
        }
        String index = annotation.index();//索引字段
        String type = annotation.type();// 类型
        if (StringUtils.isEmpty(index) || StringUtils.isEmpty(type)) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解属性 indexName 与 typeName");
        }

        BulkRequestBuilder bulkRequest = getClient().prepareBulk();
        IndexRequest request = null;
        try {
            for (Object t : list) {
                Field field = t.getClass().getDeclaredField("id");
                field.setAccessible(true);
                String id = (String) field.get(t);
                String json = JSON.toJSONString(t);
                request = getClient().prepareIndex(index, type, id).setSource(json, XContentType.JSON).request();
//                BulkRequestBuilder builder = client.prepareBulk();
//                IndexRequestBuilder request = client.prepareIndex("lib2","books","8").setSource(
//                        XContentFactory.jsonBuilder()
//                                .startObject()
//                                .field("title","python")
//                                .field("price",99)
//                                .endObject()
//                );
//                IndexRequestBuilder request2 = client.prepareIndex("lib2","books","9").setSource(
//                        XContentFactory.jsonBuilder()
//                                .startObject()
//                                .field("title","VR")
//                                .field("price",29)
//                                .endObject()
//                );
//                builder.add(request);
//                builder.add(request2);
////该方法ES默认是分片1秒钟后刷新，即插入成功后马上查询，插入的数据不能马上被查出
//                BulkResponse response = builder.get();
//                System.out.println(response.status());


                bulkRequest.add(request);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        bulkRequest.execute().actionGet();
    }

    /**
     * 根据id查询数据
     *
     * @param clx    返回类的class
     * @param idList 查询数据的idList
     * @return t
     */
    public static <T> List<T> getObjectByIdList(Class<T> clx, List<String> idList) throws Exception {
        List<T> resultList = new ArrayList<>();
        ESAnnotation annotation = clx.getAnnotation(ESAnnotation.class);
        if (null == annotation) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解");
        }
        String index = annotation.index();//索引字段
        String type = annotation.type();// 类型
        if (StringUtils.isEmpty(index) || StringUtils.isEmpty(type)) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解属性 indexName 与 typeName");
        }
        MultiGetResponse responses = getClient().prepareMultiGet()
                .add(index, type, idList) // 多个id的方式
                .get();
        responses.getResponses()[0].getResponse().getSourceAsMap();
        MultiGetItemResponse[] multis = responses.getResponses();
        if (null != multis && multis.length > 0) {
            for (MultiGetItemResponse res : multis) {
                Map<String, Object> sourceAsMap = res.getResponse().getSourceAsMap();
                resultList.add(mapToPOJO(sourceAsMap, clx));
            }
        }
        return resultList;
    }

    /**
     * 根据id查询数据
     *
     * @param clx 返回类的class
     * @param id  查询数据的id
     * @return t
     */
    public static <T> T getObjectById(Class<T> clx, String id) throws Exception {
        ESAnnotation annotation = clx.getAnnotation(ESAnnotation.class);
        if (null == annotation) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解");
        }
        String index = annotation.index();//索引字段
        String type = annotation.type();// 类型
        if (StringUtils.isEmpty(index) || StringUtils.isEmpty(type)) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解属性 indexName 与 typeName");
        }
        GetResponse response = getClient().prepareGet(index, type, id).get();
        Map<String, Object> sourceAsMap = response.getSourceAsMap();
        if (null == sourceAsMap || sourceAsMap.size() == 0) {
            return clx.newInstance();
        }
        return mapToPOJO(sourceAsMap, clx);
    }

    /**
     * @describe 例:map中有key为"id",value为"001"的数据,类对象为User,User中有Spring id;属性,
     * 返回值:返回User对象,你将获得一个id属性为"001"的User对象
     */
    public static <T> T mapToPOJO(Map map, Class<T> clazz) throws Exception {
        //通过class对象拿到所有的字段(包括私有)
        Field[] declaredFields = clazz.getDeclaredFields();
        //通过class对象拿到实例对象,虽然此时它是Object类型
        T t = clazz.newInstance();
        //循环Field[]拿到每个属性对象
        String key = "";
        ESField annotation = null;
        for (Field field : declaredFields) {
            key = field.getName();
            //打开属性对象的赋值权限
            field.setAccessible(true);
            annotation = field.getAnnotation(ESField.class);
            if (null != annotation && !StringUtils.isEmpty(annotation.name())) {
                key = field.getName();
            }
            if (map.get(key) != null) {
                //然后通过map.get(field.getName())取到map里面的值field.set()进实例对象
                if (field.getType() == Date.class) {
                    field.set(t, DateUtil.longToDate((Long) map.get(key)));
                } else {
                    field.set(t, map.get(key));
                }
            }
        }
        //我们把Object转成泛型返回
        return t;
    }


    /**
     * 创建索引与mapping模板，类需要添加 @ESAnnotation注解
     *
     * @param clx es类的class
     * @throws IOException
     */
    public static <T>void createMapping(Class<T> clx) throws IOException {
        //获取类上配置的注解
        ESAnnotation annotation = clx.getAnnotation(ESAnnotation.class);
        if (null == annotation) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解");
        }
        String index = annotation.index();//索引字段
        String type = annotation.type();// 类型

        if (StringUtils.isEmpty(index) || StringUtils.isEmpty(type)) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解属性 indexName 与 typeName");
        }

        CreateIndexRequestBuilder cib = getClient().admin().indices().prepareCreate(index);
        XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("properties");
        Field[] fields = clx.getDeclaredFields();
        ESField esField = null;
        for (Field field : fields) {
            esField = field.getAnnotation(ESField.class);
            if (null != esField) {
                mapping.startObject(esField.name()).field("type", esField.type()).field("index", esField.index()).endObject();
            }
        }
        mapping.endObject().endObject();
        cib.addMapping(type, mapping).get();
    }

    /**
     * 查询具体类的mapping
     *
     * @param clx es 实体类，类需要添加 @ESAnnotation注解
     * @return map
     */
    public static <T>Map<String, String> selectMapping(Class<T> clx) {
        ESAnnotation annotation = clx.getAnnotation(ESAnnotation.class);
        if (null == annotation) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解");
        }
        String index = annotation.index();//索引字段
        if (StringUtils.isEmpty(index)) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解属性 indexName");
        }

        Map<String, String> resultMap = new HashMap<>();
        ImmutableOpenMap<String, MappingMetaData> mappingsByIndex =
                getClient().admin().cluster().prepareState().execute()
                        .actionGet().getState().getMetaData().getIndices()
                        .get(index).getMappings();

        for (ObjectObjectCursor<String, MappingMetaData> indexEntry : mappingsByIndex) {
            resultMap.put(indexEntry.key, indexEntry.value.source().toString());
        }
        return resultMap;
    }

    /**
     * 删除索引，index正常删除或者索引不存在，返回true，类需要添加 @ESAnnotation注解
     *
     * @param clx 添加了 @ESAnnotation注解的类class
     * @return boolean
     */
    public static <T>boolean deleteEsIndex(Class<T> clx) {
        boolean flag = true;
        ESAnnotation annotation = clx.getAnnotation(ESAnnotation.class);
        if (null == annotation) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解");
        }
        String index = annotation.index();//索引字段

        if (StringUtils.isEmpty(index)) {
            throw new RuntimeException("请检查类是否配置了 ESAnnotation 的注解属性 indexName");
        }

        //判断索引库是否存在
        IndicesExistsRequest indicesExistsRequest = new IndicesExistsRequest(index);
        IndicesExistsResponse indicesExistsResponse = getClient().admin().indices().exists(indicesExistsRequest).actionGet();
        if (indicesExistsResponse.isExists()) {
            //删除索引库
            DeleteIndexResponse response1 = getClient().admin().indices().prepareDelete(index).execute().actionGet();
            flag = response1.isAcknowledged();
        }
        return flag;
    }
}
